import axios from 'axios'
import type { Model } from '../aiModels'

// AI服务商提供者接口
export interface AIProvider {
  id: string;
  name: string;
  description: string;
  baseUrlTemplate: string;
  fetchModels(baseUrl: string, apiKey: string): Promise<Model[]>;
  getDefaultModels(): Model[];
  getHeaders(apiKey: string): Promise<Record<string, string>> | Record<string, string>;
  
  // 新增流式响应处理方法
  streamContent(options: StreamContentOptions): Promise<void>;
  // 非流式响应方法
  callContent(prompt: string | Array<{role: string, content: string}> | {system?: string, user?: string}, apiKey: string, baseUrl: string): Promise<string>;
}

// 流式内容请求的选项接口
export interface StreamContentOptions {
  prompt: string | Array<{role: string, content: string}> | {system?: string, user?: string};
  apiKey: string;
  baseUrl: string;
  model: string;
  presetWords?: string[];
  onToken?: (token: string) => void;
  onError?: (error: Error) => void;
  onFinish?: () => void;
  setGenerating?: (status: boolean) => void;
}

// 基础AI提供商抽象类 - 实现一些通用逻辑
export abstract class BaseAIProvider implements AIProvider {
  id: string;
  name: string;
  description: string;
  baseUrlTemplate: string;

  constructor(id: string, name: string, description: string, baseUrlTemplate: string) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.baseUrlTemplate = baseUrlTemplate;
  }

  abstract getDefaultModels(): Model[];
  
  // 新增抽象方法，强制子类实现
  abstract streamContent(options: StreamContentOptions): Promise<void>;
  
  // 非流式响应的默认实现，子类可以覆盖
  async callContent(prompt: string | Array<{role: string, content: string}> | {system?: string, user?: string}, apiKey: string, baseUrl: string): Promise<string> {
    throw new Error(`Provider ${this.name} does not implement callContent method`);
  }

  getHeaders(apiKey: string): Promise<Record<string, string>> | Record<string, string> {
    return {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };
  }

  async fetchModels(baseUrl: string, apiKey: string): Promise<Model[]> {
    try {
      if (!apiKey || !baseUrl) {
        console.warn(`API Key或地址未设置，将返回默认模型列表`);
        return this.getDefaultModels();
      }

      const response = await axios.get(`${baseUrl}/v1/models`, {
        headers: await Promise.resolve(this.getHeaders(apiKey)),
        withCredentials: false,
        timeout: 30000,
      });

      console.log(`[${this.name}] API响应状态:`, {
        status: response.status,
        statusText: response.statusText,
      });

      let modelList: any[] = [];

      if (response.data?.data && Array.isArray(response.data.data)) {
        // OpenAI 标准格式
        modelList = response.data.data;
      }
      else if (Array.isArray(response.data)) {
        // 直接数组格式
        modelList = response.data;
      }
      else if (typeof response.data === 'object') {
        // 对象格式，尝试提取models字段
        modelList = response.data.models || response.data.items || [];
      }

      if (modelList && modelList.length > 0) {
        return this.processModels(modelList);
      }

      return this.getDefaultModels();
    }
    catch (error) {
      console.error(`[${this.name}] 获取模型列表失败:`, error);
      return this.getDefaultModels();
    }
  }

  // 处理流式响应的内部通用方法
  protected async processStreamResponse(
    response: Response,
    onToken?: (token: string) => void,
    onFinish?: () => void,
    setGenerating?: (status: boolean) => void
  ) {
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    if (!reader) {
      throw new Error(`无法读取响应数据流`);
    }

    while (true) {
      const { done, value } = await reader.read();

      if (done) {
        if (setGenerating) {
          setGenerating(false);
        }
        onFinish?.();
        break;
      }

      const chunk = decoder.decode(value);
      const lines = chunk.split(`\n`);

      for (const line of lines) {
        if (line.startsWith(`data: `)) {
          const data = line.slice(6);
          if (data === `[DONE]`)
            continue;

          try {
            const parsed = JSON.parse(data);
            // 通用API返回格式适配
            const token = parsed.choices?.[0]?.delta?.content || 
                          parsed.choices?.[0]?.message?.content || 
                          parsed.delta?.content || 
                          parsed.content || 
                          '';
                          
            // GitHub Copilot/Claude专用格式适配
            if (!token && parsed.type === 'content_block_delta') {
              const claudeToken = parsed.delta?.text || '';
              if (claudeToken) {
                onToken?.(claudeToken);
              }
            } else if (token) {
              onToken?.(token);
            }
          }
          catch (e) {
            console.error(`解析响应数据失败:`, e);
            console.debug(`原始数据:`, line);
          }
        }
      }
    }
  }

  // 处理模型数据
  protected processModels(modelList: any[]): Model[] {
    return modelList.map((model: any) => {
      const id = model.id || model.model_id || model.name || '';
      const name = model.name || id;
      
      // 根据模型ID设置默认的maxTokens
      let maxTokens = model.max_tokens || model.maxTokens || 0;
      if (maxTokens === 0) {
        if (id.includes('gpt-4')) {
          maxTokens = 8192;
        }
        else if (id.includes('gpt-3.5')) {
          maxTokens = 4096;
        }
      }

      return {
        id,
        name,
        maxTokens,
        available: true,
      };
    }).filter(model => model.id); // 过滤掉没有id的模型
  }
} 